package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSClient;
import com.changgou.file.pojo.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            if (file==null){
                return new Result(false,StatusCode.ERROR,"文件不存在");
            }
            //获取完整文件名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                return new Result(false,StatusCode.ERROR,"文件不存在");
            }
            //获取文件扩展名
            String exName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件的内容
            byte[] fileBytes = file.getBytes();
            //创建文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,fileBytes,exName);
            //基于工具类进行文件上传
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
            String url = FastDFSClient.getTrackerUrl()+"/"+upload[0]+"/"+upload[1];
            return new Result(true,StatusCode.OK,"文件上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "文件上传错误");
        }
    }
}
